package org.cb.core;

import java.awt.Canvas;
import org.cb.client.Client;
import org.cb.gui.MainGUI;

/**
 * 
 * @author Unknown
 * 
 * This will manage our canvas.
 * 
 * In the event scapegoat replaces the canvas.
 * This should fix it's self within 5 seconds.
 *
 */
public class CanvasManager {
	
	/**
	 * Create a new CanvasManager
	 */
	public CanvasManager(){
		Thread cManager = new Thread() {
			@Override
			public void run(){
				AIloop();
			}
		};
		cManager.start();
	}
	
	/**
	 * Loop every 5 seconds.
	 */
	public void AIloop(){
		while(true){
			
			update();
			
		    try {
		    	Thread.sleep(5000);
		    }catch(InterruptedException ex){}
		}
	}
	
	/**
	 * Make sure the canvas is up to date.
	 */
	public Canvas update(){
		if(Global.getTheCanvas() == null) {
			try{
				Global.setTheCanvas((Canvas)Client.applet.getComponentAt(1, 1));
			}catch(Exception e){e.printStackTrace();}
			
			return Global.getTheCanvas();
		}
		
		
		if (!Client.applet.getComponentAt(1, 1).equals(Global.getTheCanvas())) {
			MainGUI.log("Trying to update the canvas.");
			try{
				Global.setTheCanvas((Canvas)Client.applet.getComponentAt(1, 1));
			}catch(Exception e){e.printStackTrace();}
			
			return null;
		}
		
		return Global.getTheCanvas();
	}

}
